package controller

import (
	"github.com/Unknwon/com"
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"hytx_manager/middleware/auth"
	"hytx_manager/models"
	"hytx_manager/pkg/app"
	"hytx_manager/pkg/e"
	"hytx_manager/pkg/setting"
	"net/http"
	"strconv"
	"time"
)

func GetMediaUsers(c *gin.Context) {
	//appG := app.Gin{c}
	status := com.StrTo(c.Query("status")).MustInt()
	identity := com.StrTo(c.Query("identity")).MustInt()
	phone := c.Query("phone")
	begin_time := c.Query("begin_time")
	end_time := c.Query("end_time")
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", strconv.Itoa(setting.AppSetting.PageSize)))
	data, paginate := models.GetMediaUsersAll(status, identity, begin_time, end_time, phone, page, limit)
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "ok",
		"data": gin.H{
			"paginate": paginate,
			"data":     data,
		},
	})
}

func GetMediaUserInfoById(c *gin.Context) {
	appG := app.Gin{c}
	id := com.StrTo(c.Query("id")).MustInt()
	valid :=  validation.Validation{}
	valid.Min(id, 1,"id").Message("id必须大于1！")

	identity := com.StrTo(c.Query("identity")).MustInt()
	if identity == 1 {
		data, err := models.GetMediaUserInfoById(id)
		if err != nil {
			appG.Response(http.StatusOK, e.ERROR, err)
		}
		appG.ResponseMsg(200, "", data)
	} else {
		data, err := models.GetMediaUserInfoInstitution(id)
		if err != nil {
			appG.Response(http.StatusOK, e.ERROR, err)
		}
		appG.ResponseMsg(200, "", data)
	}

}

func UpdateMediaUserStatus(c *gin.Context)  {
	appG := app.Gin{c}
	id := com.StrTo(c.Query("id")).MustInt()
	status :=  com.StrTo(c.Query("status")).MustInt()
	remarks := c.Query("remarks")

	if err := models.UpdateMediaUserStatus(id ,status, remarks); err != nil{
		appG.Response(http.StatusOK, e.ERROR, err)
		return
	}
	msg := models.NewMessage()
	msg.Type = 2
	msg.From = auth.User(c).ID
	msg.To = id
	msg.Target = id
	msg.CreatedAt = time.Now()
	msg.Send()
	title := "你的账号现在"
	switch status {
	case 1:
		title += "待审核"
	case 2:
		title += "未通过"
	case 3:
		title += "已认证"

	}
	msg.SetContent(title, "")
	appG.ResponseMsg(200, "设置成功！", "")
}

func MediaAble(c *gin.Context) {
	id,_ := strconv.Atoi(c.Query("id"))
	status, _ := strconv.Atoi(c.Query("status"))
	models.DB.Table("media_users").Where("id=?", id).Update("is_enabled", status)

	msg := models.NewMessage()
	msg.Type = 2
	msg.From = auth.User(c).ID
	msg.To = id
	msg.Target = id
	msg.CreatedAt = time.Now()
	msg.Send()
	var title  string
	switch status {
	case 0:
		title = "账号被管理员‘"+auth.User(c).Username+"’启用"
	case 1:
		title = "账号被管理员‘"+auth.User(c).Username+"’禁用"
	}
	msg.SetContent(title, "")
	success(c)
}